<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2016-10-17
 * Time: 8:57
 */
namespace app\src\user\action;


use app\src\account\enmu\AccountEnmu;
use app\src\base\action\BaseAction;
use app\src\base\facade\AccountFacade;
use app\src\base\helper\ValidateHelper;
use app\src\filiation\action\FiliationAction;
use app\src\invite\action\InviteCodeAction;
use app\src\user\facade\DefaultUserFacade;
use app\src\user\model\UcenterMember;

class RegisterAction extends BaseAction
{
    protected  $facade;

    public function getUserFacade(){
        $this->facade = new AccountFacade(new DefaultUserFacade());
        return $this->facade;
    }

    public function register($entity){
        
        $result = $this->getUserFacade()->register($entity);
        return $this->result($result);
    }

    public function registerProcess($nickname, $username, $country, $password, $email = '', $invite_code = '', $wxopenid = '')
    {

        $reg_from = 0;
        $reg_type = UcenterMember::ACCOUNT_TYPE_USERNAME;
        $mobile = "";

        if(ValidateHelper::isMobile($username)) {
            if(empty($country)){
                return $this->error(lang('country_tel_number_need'));
            }

            $mobile = $username;
            $username = 'm_' . $mobile;
            $reg_type = UcenterMember::ACCOUNT_TYPE_MOBILE;
        }else{
            //手机号等于微信号
            $mobile = $username;
        }

        if(empty($email)){
            $email = $username.'@itboye.com';
        }

        $entity = array(
            'nickname'=>$nickname,
            'username'=>$username,
            'password'=>$password,
            'mobile'=>$mobile,
            'email'=>$email,
            'country'=>$country,
            'reg_from'=>$reg_from,
            'reg_type'=>$reg_type,
            'wxopenid'=>$wxopenid
        );

        //1. 校验验证码

        //2. 校验邀请码
        if(!empty($invite_code) && $invite_code){
            $result = (new InviteCodeAction)->check($invite_code);
            if(!$result['status']) return $this->error('错误的邀请码');
        }

        //3. 调用注册操作
        $action = new RegisterAction();
        $result = $action->register($entity);

        if($result['status'] && intval($result['info']) > 0){

            $uid = $result['info'];

            //4. 根据邀请码添加关系
            if(!empty($invite_code) && $invite_code){
                (new FiliationAction)->addByInviteCode($uid, $invite_code);
            }

            //5. 生成邀请码
            (new InviteCodeAction)->create(AccountEnmu::USER, $uid);

            return $this->success(lang("success"));
        }

        if(is_string($result['info'])){
            return $this->error($result['info']);
        }

        return $this->error(lang("fail"));
    }

}